package com.demo.auth.service;

import com.demo.auth.dto.AuthResponse;
import com.demo.auth.dto.LoginRequest;
import com.demo.auth.dto.RegisterRequest;
import com.demo.auth.entity.User;
import com.demo.auth.enums.Role;
import com.demo.auth.mapper.UserMapper;
import com.demo.auth.util.JwtUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public UserService(UserMapper userMapper, PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    public AuthResponse register(RegisterRequest request) {
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }

        if (userMapper.existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        User user = new User(request.getUsername(), passwordEncoder.encode(request.getPassword()));
        userMapper.insertUser(user);

        String token = jwtUtil.generateToken(user.getUsername(), user.getRole());
        return new AuthResponse(token, user.getUsername(), user.getRole().getCode(), "注册成功");
    }

    public AuthResponse login(LoginRequest request) {
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        String token = jwtUtil.generateToken(user.getUsername(), user.getRole());
        return new AuthResponse(token, user.getUsername(), user.getRole().getCode(), "登录成功");
    }

    public User getCurrentUser(String username) {
        return userMapper.findByUsername(username);
    }

    // 管理员功能
    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }

    public List<User> getUsersByRole(Role role) {
        return userMapper.findUsersByRole(role);
    }

    public void updateUserRole(Long userId, Role role) {
        userMapper.updateUserRole(userId, role);
    }

    public void updateUserEnabled(Long userId, Boolean enabled) {
        userMapper.updateUserEnabled(userId, enabled);
    }
}